<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * 显示树形编辑菜单
 * @param  arr  $data  要处理的数据
 * @param  int  $Id    父级id
 * @param  INT $level 层级
 * @return html         返回html
 */
function getTree($data, $Id, $level = 0)
{
    $html = '';
    foreach ($data as $k => $v) {
        if ($v['pid'] == $Id) {
            //父亲找到儿子
            if (isset($v['checked']) && $v['checked'] == 'y') {
                //设置选中状态
                $html .= "<li class=\"auth-t" . $level . "\" data-level=\"" . $level . "\"><input type=\"checkbox\" name=\"rules[]\" lay-skin=\"primary\" title=\"" . $v['title'] . "\" value=\"" . $v['id'] . "\" checked=\"\" lay-checkbox lay-filter=\"formauth\">";
            } else {
                $html .= "<li class=\"auth-t" . $level . "\" data-level=\"" . $level . "\"><input type=\"checkbox\" name=\"rules[]\" lay-skin=\"primary\" title=\"" . $v['title'] . "\" value=\"" . $v['id'] . "\" lay-checkbox lay-filter=\"formauth\" >";
            }
            $html .= getTree($data, $v['id'], $level + 1);
            $html = $html . "</li>\r\n";
        }
    }
    return $html ? '<ul>' . $html . '</ul>' : $html;
}
/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) {
        $size /= 1024;
    }

    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 管理员操作日志
 * @param  [type] $data [description]
 * @return [type]       [description]
 */
function addlog($operation_id = '', $str = '')
{
    // //获取网站配置
    // $web_config = config('webconfig.is_log');
    // if ($web_config == 1) {
    //     $data['operation_id'] = $operation_id; //操作id
    //     $data['user_id']      = session('userid'); //管理员id
    //     $data['ip']           = \Request::ip(); //操作ip
    //     $data['create_time']  = time(); //操作时间
    //     $url['module']        = \Request::module();
    //     $url['controller']    = \Request::controller();
    //     $url['function']      = \Request::action();

    //     $strurl = $url['controller'] . '/' . $url['function'];

    //     if ($url['controller'] != 'Login') {
    //         //登录退出时不
    //         $data['menu_id'] = \Db::name('auth_rule')->where([['module', '=', $url['module']], ['name', '=', $strurl]])->value('id');
    //     } else {
    //         $data['menu_id'] = 1;
    //     }

    //     $data['menu_id'] = $data['menu_id'] ? $data['menu_id'] : 1;

    //     $data['url']  = $url['controller'] . '/' . $url['function'];
    //     $data['text'] = $str;

    //     \Db::name('admin_log')->insert($data);
    // } else {
    //     //关闭了日志
    //     return true;
    // }
    return true;
}

/**
 * 生成配制处表单
 * @param  [type] $fied 表单字段名
 * @param  [type] $val  表单值
 * @param  [type] $type 表单类型
 * @return [type]       [description]
 */
function createform($fied, $val, $type, $typeval)
{
    $html = '';
    if ($type == 1) {
        $html = '<textarea class="layui-textarea" name="' . $fied . '" lay-verify="content">' . $val . '</textarea>';
    } elseif ($type == 2) {
        //下拉
        $html .= '<select name="' . $fied . '" lay-verify="required" class="type-name" lay-filter="test">';
        if (!empty($typeval)) {
            $tes = array_unique(explode(',', $typeval));
            $tes = array_filter($tes);
            foreach ($tes as $k => $v) {
                $vs      = explode('|', $v);
                $vs[1]   = (isset($vs[1])) ? $vs[1] : $vs[0];
                $checked = ($val == $vs[0]) ? 'checked=""' : '';
                $html .= '<option value="' . $vs[0] . '">' . $vs[1] . ' ' . $checked . ' </option>';
            }
        }
        $html .= '</select>';
    } elseif ($type == 3) {
        //开关
        if (!empty($typeval)) {
            $tes = array_unique(explode(',', $typeval));
            $tes = array_filter($tes);
            foreach ($tes as $k => $v) {
                $vs      = explode('|', $v);
                $vs[1]   = (isset($vs[1])) ? $vs[1] : $vs[0];
                $checked = ($val == $vs[0]) ? 'checked=""' : '';
                $html .= '<input type="radio" name="' . $fied . '" value="' . $vs[0] . '" title="' . $vs[1] . '" ' . $checked . '>';

            }

        }
    } elseif ($type == 4) {
        //多选
        if (!empty($typeval)) {
            $tes = array_unique(explode(',', $typeval));
            $tes = array_filter($tes);
            foreach ($tes as $k => $v) {
                $vs      = explode('|', $v);
                $vs[1]   = (isset($vs[1])) ? $vs[1] : $vs[0];
                $checked = ($val == $vs[0]) ? 'checked=""' : '';
                $html .= '<input type="checkbox" name="' . $fied . '" lay-skin="primary" title="' . $vs[1] . '" checked="" value="' . $val . '" ' . $checked . '>';

            }

        }

    } else {
        $html = '<input type="text" name="' . $fied . '" lay-verify="title" autocomplete="off" class="layui-input" value="' . $val . '">';
    }
    return $html;
}

function ahuthbtn($act = '')
{
    if (empty($act)) {
        return false;
    }
    $auth = new \my\Auth();
    if (!$auth->check(\Request::controller() . '/' . $act, UID) && UID != '1') {
        return false;
    }
    return true;

}
/**
 * 连接外部数据库表
 * @param int $uid   当前区服id
 * @param str $str   表前缀，限定，游戏 game ,用户 user , 日志 log
 * @param [type] $table 要操作的数据表
 */
function CreateGameModel($uid, $str)
{
    if (!$uid && !$str) {
        return null;
    }

    if ($str == 'game' || $str == 'user' || $str == 'log') {
        $dbconifg = \Db::name('partition')->where([['status', '=', 1], ['id', '=', $uid]])->value($str . 'db');
        if (empty($dbconifg)) {
            $platform_id = \Db::name('partition')->where([['status', '=', 1], ['id', '=', $uid]])->value('platform_id');
            $dbconifg    = \Db::name('platform')->where([['status', '=', 1], ['id', '=', $platform_id]])->value($str . 'db');
            //$partitionurl = Db::name('partition')->field("b.http as http")->alias('a')->join('platform b','a.platform_id = b.id','left')->where([['a.status','=',1],['b.status','=',1]])->find();
        }
        if (empty($dbconifg)) {
            return false;
        }
        $dbconifg = unserialize($dbconifg);
    }

    $config = [
        // 数据库类型
        'type'     => 'mysql',
        // 服务器地址
        'hostname' => $dbconifg['host'],
        // 数据库名
        'database' => $dbconifg['name'],
        // 数据库用户名
        'username' => $dbconifg['user'],
        // 数据库密码
        'password' => $dbconifg['pass'],
        // 数据库连接端口
        'hostport' => $dbconifg['port'],
    ];
    return Db::connect($config);
    //$model = M()->db(1, $config)->table($table);
    //return $model;
}

function PostGameCUrl($url, $post)
{
    header("content-type:text/html;charset=utf-8");
    $data = json_encode($post);
    echo $data;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $result = curl_exec($ch); #这个是读到的值
    if (curl_errno($ch)) {
        print_r(curl_error($ch));
    }
    curl_close($ch);
    unset($ch);
    return $result;
    //return json_decode($result, true);
}

/**
 * 模拟post进行url请求
 * @param string $url
 * @param string $param
 */
function request_post($url = '', $param = '')
{
    if (empty($url) || empty($param)) {
        return false;
    }
    $postUrl  = $url;
    $curlPost = $param;
    $ch       = curl_init(); //初始化curl
    curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $data = curl_exec($ch); //运行curl
    curl_close($ch);
    return $data;
}

function Hour($value = '')
{
    return date('h', $value);
}

/**
 * 读取指定 位置的src配置文件
 */
function writeSrctxt($str)
{
    if (empty($str)) {return false;}
    $file = './srcData/' . $str . '.txt';
    if (!file_exists($file)) {return false;}
    $str          = file_get_contents($file);
    $str_encoding = mb_convert_encoding($str, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5'); //转换字符集（编码）
    $array        = explode("\r\n", $str_encoding);
    $narr         = [];
    $array        = array_filter($array);
    foreach ($array as $k => $v) //遍历循环
    {
        $narr[$k] = array_filter(explode("|", $v));
    }
    return array_filter($narr);
}
